package com.example.foo.admin.task;

import com.ruoyi.common.utils.StringUtils;
import com.example.foo.order.model.Order;
import com.example.foo.order.service.OrderService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component("deliveryTask")
public class DeliveryTask {

    private static Logger log = LoggerFactory.getLogger(DeliveryTask.class);

    @Autowired
    private OrderService orderService;

    public void AutoTakeDelivery(String offsetDay){
        log.info(StringUtils.format("自动确认收货任务： 字符串类型{} ", offsetDay));
        try {
            Date now = new Date();
            Date dtime = DateUtils.addDays(now, Integer.parseInt(offsetDay));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String beforeTenDay = sdf.format(dtime);
            //查询10天前所有已发货状态的订单
            List<Order> orders = orderService.findOrdersByStatus(Order.Status.delivery.val,beforeTenDay);
            if(orders.size() > 0){
                for(Order order : orders){
                    //修改状态为已收货
                    order.setStatus(Order.Status.takeDelivery.val);
                    orderService.updateOrder(order);
                    log.info(StringUtils.format("自动确认收货订单号：{} ", order.getOutTradeNo()));
                }
            }else{
                log.error("没有可确认收货的订单");
            }
        } catch (Exception e) {
            log.error("自动确认收货异常："+e.getMessage(), e);
        }
    }
}
